package com.gitee.melin.bee.core.jdbc.relational;

import com.gitee.melin.bee.core.jdbc.enums.FileFormat;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.Data;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

@Data
public class MetaTable implements Serializable, Comparable<MetaTable> {

    private static final long serialVersionUID = 4209205512472367171L;

    private String schemaName;

    private String tableName;

    private String location;

    private FileFormat fileFormat = FileFormat.UNKNOW;

    private String comment;

    private BeeTableType tableType = BeeTableType.UNKNOW;

    private boolean partition = false;

    private String engine;

    private Long dataSize;

    private Long numRows;

    private Long numFiles;

    private Date createTime;

    private Date updateTime;

    private Date lastDdlTime;

    private List<MetaColumn> columns;

    private List<String> partitionKeys = new ArrayList<>();

    private Map<String, Object> properties;

    public MetaTable() {}

    public MetaTable(String tableName) {
        this.tableName = tableName;
    }

    public MetaTable(String schemaName, String tableName) {
        this.schemaName = schemaName;
        this.tableName = tableName;
    }

    public String getSchemaTableName() {
        return StringUtils.isBlank(schemaName) ? tableName : schemaName + "." + tableName;
    }

    public List<String> getPrimaryKeys() {
        return columns.stream()
                .filter(MetaColumn::isPrimaryKey)
                .map(MetaColumn::getColumnName)
                .collect(Collectors.toList());
    }

    @Override
    public String toString() {
        return "MetaTable{"
                + ", schemaName='"
                + schemaName
                + '\''
                + ", tableName='"
                + tableName
                + '\''
                + ", location='"
                + location
                + '\''
                + ", fileFormat="
                + fileFormat
                + ", comment='"
                + comment
                + '\''
                + ", tableType="
                + tableType
                + ", partition="
                + partition
                + ", columns="
                + columns
                + ", properties="
                + properties
                + ", partitionKeys="
                + partitionKeys
                + '}';
    }

    @Override
    public int compareTo(MetaTable o) {
        return this.tableName.compareTo(o.getTableName());
    }

    public String getColMetadataMd5() {
        if (this.getColumns() == null) {
            return null;
        }
        return DigestUtils.md5Hex(StringUtils.join(this.getColumns(), ";"));
    }
}
